﻿using JTG.ServiceInterface;
using JTG.ServiceInterface.Factory;
using JTG.ServiceInterface.Model;
using System;
using System.Collections.Generic;
using System.Threading;
using Tzw.Common;

namespace JTG.CheckInMachine
{
    /// <summary>
    /// 读取卡信息
    /// </summary>
    public partial class ReadCard : BaseForm
    {
        private CheckInType _checkInType;
        private int _timeOutClose = App.GlobSettings.OperateShowTimes;
        private bool _isLoadData;

        public ReadCard(CheckInType type)
        {
            InitializeComponent();

            _checkInType = type;
            switch (type)
            {
                case CheckInType.Card:
                    MusicPlay.PlayMusic($"{Environment.CurrentDirectory}\\Voice\\请按图示刷就诊卡.mp3");
                    BackgroundImage = Properties.Resources.swipe_card;
                    break;
                case CheckInType.WxQrCode:
                    MusicPlay.PlayMusic($"{Environment.CurrentDirectory}\\Voice\\请扫描微信公众号的个人条码.mp3");
                    BackgroundImage = Properties.Resources.wx_qrcode;
                    break;
                case CheckInType.ElectronicCard:
                    MusicPlay.PlayMusic($"{Environment.CurrentDirectory}\\Voice\\请扫描电子健康卡二维码.mp3");
                    break;
            }

            textBox1.GotFocus += TextBox1_GotFocus;
            lab_time.Text = DateTime.Now.ToString("HH:mm:ss");

            keyboard.NumberEvent += NumberEvent;
            keyboard.OkEvent += OkEvent;
            keyboard.CleanEvent += CleanEvent;
            keyboard.DeleteEvent += DeleteEvent;
        }

        #region 键盘事件

        private void NumberEvent(object sender, EventArgs e)
        {
            textBox1.Text += sender.ToString();
            _timeOutClose = App.GlobSettings.OperateShowTimes;
        }

        private void OkEvent(object sender, EventArgs e)
        {
            btn_ok_Click(sender, e);
            _timeOutClose = App.GlobSettings.OperateShowTimes;
        }

        private void DeleteEvent(object sender, EventArgs e)
        {
            if (textBox1.Text.Length > 0)
                textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
            _timeOutClose = App.GlobSettings.OperateShowTimes;
        }

        private void CleanEvent(object sender, EventArgs e)
        {
            textBox1.Text = "";
            _timeOutClose = App.GlobSettings.OperateShowTimes;
        }

        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            lab_time.Text = DateTime.Now.ToString("HH:mm:ss");

            //请求数据中，界面不计时
            if (!_isLoadData)
                _timeOutClose--;
            if (_timeOutClose == 0)
            {
                timer1.Enabled = false;
                Close();
            }

            lab_TimeOut.Text = _timeOutClose.ToString();
        }

        private void TextBox1_GotFocus(object sender, EventArgs e)
        {
            textBox1.Select(0, textBox1.Text.Length);
        }

        /// <summary>
        /// 回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textBox1.Text)) return;

                textBox1.Text = textBox1.Text.Split(':')[0];//电子卡，取第一个冒号（:）前面的内容

                _isLoadData = true;
                textBox1.Enabled = false;
                lab_loading.Visible = true;
                _timeOutClose = App.GlobSettings.OperateShowTimes;

                new Thread(() =>
                {
                    string errorMsg = null;
                    try
                    {
                        //签到服务接口初始化
                        var checkInService = new CheckInServiceFactory().CreateCheckInService();
                        if (checkInService == null)
                        {
                            errorMsg = "接口初始化错误，请联系管理员";
                            return;
                        }

                        //查询签到信息
                        var registerInfo = checkInService.GetRegisterInfo(textBox1.Text, _checkInType);
                        if (!string.IsNullOrEmpty(registerInfo.ErrorMsg))
                        {
                            errorMsg = registerInfo.ErrorMsg;
                            return;
                        }

                        //签到
                        var checkInResult = checkInService.CheckIn(registerInfo);
                        if (!string.IsNullOrEmpty(checkInResult.ErrorMsg))
                        {
                            errorMsg = registerInfo.ErrorMsg;
                            return;
                        }

                        try
                        {
                            Logger.Default.Info("显示签到成功");

                            switch (checkInResult.SingStatus)
                            {
                                //判断签到状态,打印签到信息
                                case SignStatus.Success:
                                case SignStatus.BackSign:
                                case SignStatus.Passed:
                                {
                                    //检查打印机状态 TODO
                                    //设置默认打印机 TODO

                                    //初始化打印信息
                                    var fillDataSet = new List<SignInfo>
                                    {
                                        checkInResult
                                    }.FillDataSet();

                                    //打印签到信息
                                    ReportHelper.Print(fillDataSet, "signinfo");

                                    break;
                                }
                            }

                            Invoke(new Action(() => { CheckInResult(checkInResult); }));

                        }
                        catch(Exception ex)
                        {
                            Logger.Default.Error("展示签到界面异常" + ex.Message + ex.StackTrace);
                        }
                    }
                    catch (Exception ex)
                    {
                        errorMsg = ex.Message;

                        Logger.Default.Error("签到异常：" + ex.Message + ex.StackTrace);
                    }
                    finally
                    {
                        try
                        {
                            Invoke(new Action(() =>
                            {
                                _isLoadData = false;
                                textBox1.Enabled = true;
                                lab_loading.Visible = false;
                                _timeOutClose = App.GlobSettings.OperateShowTimes;
                                if (!string.IsNullOrEmpty(errorMsg))
                                {
                                    ShowMsg(errorMsg);
                                }
                            }));
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }).Start();
            }
            catch (Exception ex)
            {
                Logger.Default.Error(ex.Message, ex);
                new MsgBox(ex.Message);
            }
        }

        /// <summary>
        /// 展示签到结果
        /// </summary>
        /// <param name="checkInResult"></param>
        private void CheckInResult(SignInfo checkInResult)
        {
            switch (checkInResult.SingStatus)
            {
                //判断签到状态,打印签到信息
                case SignStatus.Success:
                case SignStatus.BackSign:
                case SignStatus.Passed:
                {
                    ////展示签到信息（打印中）
                    new ShowInfo(Enums.ShowStatus.IsPrintIng, checkInResult).ShowDialog();
                    Close();

                    break;
                }
                //重复签到
                case SignStatus.SignRepeat:
                    new ShowInfo(Enums.ShowStatus.IsRepeat, checkInResult).ShowDialog();
                    Close();
                    break;
                //默认展示
                default:
                    new ShowInfo(Enums.ShowStatus.IsRepeat, checkInResult).ShowDialog();
                    Close();
                    //new MsgBox($"签到错误，请联系管理员，签到类型：{checkInResult.SingStatus}");
                    break;
            }
        }

        private void ReadCard_Load(object sender, EventArgs e)
        {
            lab_TimeOut.Text = _timeOutClose.ToString();

            //加载打印机状态 TODO
            //如果不切换打印机这不需要执行这一步 TODO
        }

        private void btn_KeyBoard_Click(object sender, EventArgs e)
        {
            keyboard.Visible = !keyboard.Visible;
        }

        public void ShowMsg(string msg)
        {
            new MsgBox(msg);
        }

        private void btn_CloseClick(object sender, EventArgs e)
        {
            Close();
        }

        private void ReadCard_Activated(object sender, EventArgs e)
        {
            textBox1.Focus();
        }
    }
}